/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.organization.impl;

import cn.hutool.crypto.SecureUtil;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.ArrayUtils;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.JEUUID;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.exception.AccountException;
import com.je.rbac.exception.OrganException;
import com.je.rbac.service.account.RbacAccountService;
import com.je.rbac.service.organization.OperationType;
import com.je.rbac.service.organization.OrgType;
import com.je.rbac.service.organization.RbacOrganizationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class RbacOrganizationServiceImpl implements RbacOrganizationService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private RbacAccountService rbacAccountService;


    @Override
    public boolean checkSystemUnique(String orgId) {
        if (!Strings.isNullOrEmpty(orgId)) {
            List<String> idList = Splitter.on(",").splitToList(orgId);
            List<DynaBean> orgBean = metaService.select(ConditionsWrapper.builder().table("JE_RBAC_ORG").in("JE_RBAC_ORG_ID", idList));
            List<String> codeList = new ArrayList<>();
            for (DynaBean dynaBean : orgBean) {
                codeList.add(dynaBean.getStr("JE_RBAC_ORG_ID"));
            }
            for (String idStr : codeList) {
                if (idStr.equals(OrgType.DEPARTMENT_ORG_ID.getCode()) || idStr.equals(OrgType.DEVELOP_ORG_ID.getCode())) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public boolean checkOrgNameUnique(DynaBean dynaBean) {
        long count = 0;
        if (Strings.isNullOrEmpty(dynaBean.getStr("JE_RBAC_ORG_ID"))) {
            count = metaService.countBySql(ConditionsWrapper.builder().table("JE_RBAC_ORG").eq("ORG_NAME", dynaBean.getStr("ORG_NAME")));
        } else {
            count = metaService.countBySql(ConditionsWrapper.builder().apply("SELECT * FROM JE_RBAC_ORG WHERE JE_RBAC_ORG_ID != {0} AND (ORG_NAME = {1})", dynaBean.getStr("JE_RBAC_ORG_ID"), dynaBean.getStr("ORG_NAME")));
        }
        if (count > 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkOrgCodeUnique(DynaBean dynaBean) {
        long count = 0;
        if (Strings.isNullOrEmpty(dynaBean.getStr("JE_RBAC_ORG_ID"))) {
            count = metaService.countBySql(ConditionsWrapper.builder().table("JE_RBAC_ORG").eq("ORG_CODE", dynaBean.getStr("ORG_CODE")));
        } else {
            count = metaService.countBySql(ConditionsWrapper.builder().apply("SELECT * FROM JE_RBAC_ORG WHERE JE_RBAC_ORG_ID != {0} AND (ORG_CODE = {1})", dynaBean.getStr("JE_RBAC_ORG_ID"), dynaBean.getStr("ORG_CODE")));
        }
        if (count > 0) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkResourceTableCodeUnique(DynaBean dynaBean) {
        long count = 0;
        if (Strings.isNullOrEmpty(dynaBean.getStr("JE_RBAC_ORG_ID"))) {
            count = metaService.countBySql(ConditionsWrapper.builder().table("JE_RBAC_ORG").eq("ORG_RESOURCETABLE_CODE", dynaBean.getStr("ORG_RESOURCETABLE_CODE")));
        } else {
            count = metaService.countBySql(ConditionsWrapper.builder().apply("SELECT * FROM JE_RBAC_ORG WHERE JE_RBAC_ORG_ID != {0} AND (ORG_RESOURCETABLE_CODE = {1})", dynaBean.getStr("JE_RBAC_ORG_ID"), dynaBean.getStr("ORG_RESOURCETABLE_CODE")));
        }
        if (count > 0) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public void updateDeptNameByOrgId(DynaBean dynaBean) {
        DynaBean orgBean = findById(dynaBean.getStr("JE_RBAC_ORG_ID"));
        if (!orgBean.getStr("ORG_NAME").equals(dynaBean.getStr("ORG_NAME"))) {
            metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET SY_ORG_NAME={0} WHERE SY_ORG_ID = {1}", dynaBean.getStr("ORG_NAME"), dynaBean.getStr("JE_RBAC_ORG_ID"));
            if (!OrgType.DEPARTMENT_ORG_ID.getCode().equals(orgBean.getStr("JE_RBAC_ORG_ID"))) {
                //外部机构修改：修改角色账号部门名称，账号部门名称
                metaService.executeSql("UPDATE JE_RBAC_ACCOUNTROLE SET ACCOUNTROLE_DEPT_NAME={0} WHERE ACCOUNTROLE_DEPT_ID = {1}", dynaBean.getStr("ORG_NAME"), dynaBean.getStr("JE_RBAC_ORG_ID"));
                metaService.executeSql("UPDATE JE_RBAC_ACCOUNTDEPT SET ACCOUNTDEPT_DEPT_NAME={0} WHERE ACCOUNTDEPT_DEPT_ID = {1}", dynaBean.getStr("ORG_NAME"), dynaBean.getStr("JE_RBAC_ORG_ID"));
            }
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public DynaBean doSave(DynaBean orgBean) {
        commonService.buildModelCreateInfo(orgBean);
        List<Map<String, Object>> countList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_ORG");
        int maxCount = (int) countList.get(0).get("MAX_COUNT");
        orgBean.set("SY_ORDERINDEX", maxCount + 1);
        metaService.insert(orgBean);
        return orgBean;
    }

    @Override
    public boolean checkOrgStatus(String tableCode) throws AccountException {
        //通过 tableCode 获取机构orgId
        DynaBean orgBean = getOrgByTableCode(tableCode);
        if (orgBean == null) {
            throw new AccountException("该人员表绑定的机构不存在，请检查是否绑定机构！");
        }
        if (orgBean.getStr("SY_STATUS").equals("0")) {
            return false;
        }
        return true;
    }

    @Override
    public DynaBean getOrgByTableCode(String tableCode) {
        return metaService.selectOne("JE_RBAC_ORG", ConditionsWrapper.builder().eq("ORG_RESOURCETABLE_CODE", tableCode));
    }

    @Override
    public DynaBean findById(String id) {
        return metaService.selectOne("JE_RBAC_ORG", ConditionsWrapper.builder().eq("JE_RBAC_ORG_ID", id));
    }

    @Override
    public DynaBean findByCode(String code) {
        return metaService.selectOne("JE_RBAC_ORG", ConditionsWrapper.builder().eq("ORG_CODE", code));
    }

    @Override
    public DynaBean findByName(String name) {
        return metaService.selectOne("JE_RBAC_ORG", ConditionsWrapper.builder().eq("ORG_NAME", name));
    }

    @Override
    public DynaBean findByTableCode(String tableCode) {
        return metaService.selectOne("JE_RBAC_ORG", ConditionsWrapper.builder().eq("ORG_RESOURCETABLE_CODE", tableCode));
    }

    @Override
    public List<DynaBean> findByTenantId(String tenantId) {
        return metaService.select("JE_RBAC_ORG", ConditionsWrapper.builder().eq("SY_TENANT_ID", tenantId));
    }

    @Override
    public List<DynaBean> findByTenantName(String tenantName) {
        return metaService.select("JE_RBAC_ORG", ConditionsWrapper.builder().eq("SY_TENANT_NAME", tenantName));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void disableOrgs(String orgIds) {
        List<String> orgIdList = Arrays.asList(orgIds.split(ArrayUtils.SPLIT));
        metaService.executeSql("UPDATE JE_RBAC_ORG SET SY_STATUS='0' WHERE JE_RBAC_ORG_ID IN ({0})", orgIdList);
        for (String orgId : orgIdList) {
            operationUserWithAccount("disable", orgId, null);
        }

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void enableOrgs(String orgIds) {
        List<String> idList = Arrays.asList(orgIds.split(ArrayUtils.SPLIT));
        metaService.executeSql("UPDATE JE_RBAC_ORG SET SY_STATUS='1' WHERE JE_RBAC_ORG_ID IN ({0})", idList);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, AccountException.class})
    public void openAccount(String orgId, String userIds, String syStatus) throws AccountException {
        List<String> userIdList = Arrays.asList(userIds.split(ArrayUtils.SPLIT));

        DynaBean orgBean = metaService.selectOne("JE_RBAC_ORG", ConditionsWrapper.builder().eq("JE_RBAC_ORG_ID", orgId));
        //获取到映射的资源表和资源表主键
        String tableCode = orgBean.getStr("ORG_RESOURCETABLE_CODE");
        String tableIdCode = orgBean.getStr("ORG_FIELD_PK");
        if (Strings.isNullOrEmpty(tableCode) || Strings.isNullOrEmpty(tableIdCode)) {
            throw new AccountException("Can't find the tableCode or pk code from the org mapping!");
        }

        //获取映射字段，账号名称、账号编码、账号手机、账号邮箱、账号性别、账号头像、角色id、角色名称、账号用户状态
        String accountNameField = orgBean.getStr("ORG_ACCOUNT_NAME");
        String accountCodeField = orgBean.getStr("ORG_ACCOUNT_CODE");
        String accountPhoneField = orgBean.getStr("ORG_ACCOUNT_PHONE");
        String accountEmailField = orgBean.getStr("ORG_ACCOUNT_MAIL");
        String accountSexField = orgBean.getStr("ORG_ACCOUNT_SEX");
        String accountAvatarField = orgBean.getStr("ORG_ACCOUNT_AVATAR");
        String accountRoleIdField = orgBean.getStr("ORG_ROLEFIELD_ID");
        String accountRoleNameField = orgBean.getStr("ORG_ROLEFIELD_NAME");
        String accountUserStatusField = orgBean.getStr("ORG_ACCOUNT_STATUS");
        String accountAccessStatusField = orgBean.getStr("ORG_ACCOUNTACCESS_STATUS");

        String defaultPassword = systemSettingRpcService.findSettingValue("JE_SYS_PASSWORD");
        if (Strings.isNullOrEmpty(defaultPassword)) {
            throw new AccountException("系统设置默认密码为空！");
        }

        List<DynaBean> accountBeanList = metaService.select("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("USER_ASSOCIATION_ID", userIdList));
        Map<String, DynaBean> hasAccountMap = new HashMap<>();
        if (accountBeanList != null && accountBeanList.size() > 0) {
            for (DynaBean eachAccountBean : accountBeanList) {
                hasAccountMap.put(eachAccountBean.getStr("USER_ASSOCIATION_ID"), eachAccountBean);

                metaService.executeSql("UPDATE " + tableCode + " SET " + accountUserStatusField + "='1' WHERE " + tableIdCode + " IN ({0})", userIdList);
            }
        }

        if (Strings.isNullOrEmpty(syStatus)) {
            //允许访问使用-
            metaService.executeSql("UPDATE " + tableCode + " SET " + accountAccessStatusField + "='1' WHERE " + tableIdCode + " IN ({0})", userIdList);
        }

        List<DynaBean> userBeans = metaService.select(tableCode, ConditionsWrapper.builder().in(tableIdCode, userIdList));
        DynaBean accountBean;
        String accountId;
        List<DynaBean> accountDeptRoleModelList = new ArrayList<>();

        for (DynaBean eachUserBean : userBeans) {
            if (hasAccountMap.containsKey(eachUserBean.getStr(tableIdCode))) {
                accountId = hasAccountMap.get(eachUserBean.getStr(tableIdCode)).getStr("JE_RBAC_ACCOUNT_ID");
                if (Strings.isNullOrEmpty(syStatus)) {
                    //允许访问使用-
                    metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET SY_STATUS='1' WHERE JE_RBAC_ACCOUNT_ID = {0}", accountId);
                }
                metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET USER_STATUS='1' WHERE JE_RBAC_ACCOUNT_ID = {0}", accountId);
            } else {
                accountId = JEUUID.uuid();
                accountBean = new DynaBean("JE_RBAC_ACCOUNT", false);
                accountBean.set("JE_RBAC_ACCOUNT_ID", accountId);
                accountBean.set("ACCOUNT_NAME", eachUserBean.getStr(accountNameField));
                accountBean.set("ACCOUNT_CODE", eachUserBean.getStr(accountCodeField));
                accountBean.set("ACCOUNT_PASSWORD", SecureUtil.md5(defaultPassword));
                accountBean.set("ACCOUNT_OPENID", JEUUID.uuid());
                accountBean.set("ACCOUNT_PHONE", eachUserBean.getStr(accountPhoneField));
                accountBean.set("ACCOUNT_MAIL", eachUserBean.getStr(accountEmailField));

                accountBean.set("ACCOUNT_SEX", eachUserBean.getStr(accountSexField));
                accountBean.set("ACCOUNT_AVATAR", eachUserBean.getStr(accountAvatarField));
                accountBean.set("USER_ASSOCIATION_ID", eachUserBean.getStr(tableIdCode));
                accountBean.set("ACCOUNT_REMARK", "通过机构创建！");
                accountBean.set("SY_ORG_ID", orgBean.getStr("JE_RBAC_ORG_ID"));
                accountBean.set("SY_ORG_NAME", orgBean.getStr("ORG_NAME"));
                accountBean.set("SY_STATUS", syStatus == null ? "1" : syStatus);
                accountBean.set("USER_STATUS", eachUserBean.getStr(accountUserStatusField));
                accountBean.set("ACCOUNT_LOCKED_STATUS", "1");
                //永久使用
                accountBean.set("ACCOUNT_PERMANENT_CODE", "1");
                //过期时间
                accountBean.set("ACCOUNT_EXPIRE_TIME", "");
                commonService.buildModelCreateInfo(accountBean);
                metaService.insert(accountBean);
            }

            if (!"0".equals(syStatus)) {
                rbacAccountService.checkAccountUnique(eachUserBean.getStr(tableIdCode), userBeans.size());
            }
            DynaBean accountDeptBean = metaService.selectOne("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder()
                    .eq("ACCOUNTDEPT_DEPT_ID", orgBean.getStr("JE_RBAC_ORG_ID")).eq("ACCOUNTDEPT_ACCOUNT_ID", accountId));
            if (accountDeptBean == null) {
                accountDeptBean = new DynaBean("JE_RBAC_ACCOUNTDEPT", false);
                accountDeptBean.set("ACCOUNTDEPT_DEPT_ID", orgBean.getStr("JE_RBAC_ORG_ID"));
                accountDeptBean.set("ACCOUNTDEPT_DEPT_NAME", orgBean.getStr("ORG_NAME"));
                accountDeptBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
                accountDeptBean.set("ACCOUNTDEPT_ACCOUNT_ID", accountId);
                accountDeptBean.set("SY_STATUS", syStatus == null ? "1" : syStatus);
                metaService.insert(accountDeptBean);
            }

            String roleIds = eachUserBean.getStr(accountRoleIdField);
            String roleNames = eachUserBean.getStr(accountRoleNameField);

            if (Strings.isNullOrEmpty(roleIds) || Strings.isNullOrEmpty(roleNames)) {
                continue;
            }

            List<String> roleIdList = Splitter.on(",").splitToList(roleIds);
            List<String> roleNameList = Splitter.on(",").splitToList(roleNames);
            DynaBean accountDeptRoleTempBean;
            for (int i = 0; i < roleIdList.size(); i++) {
                accountDeptRoleTempBean = new DynaBean("JE_RBAC_ACCOUNTROLE", false);
                accountDeptRoleTempBean.set("ACCOUNTROLE_ACCOUNT_ID", accountId);
                accountDeptRoleTempBean.set("ACCOUNTROLE_DEPT_ID", orgBean.getStr("JE_RBAC_ORG_ID"));
                accountDeptRoleTempBean.set("ACCOUNTROLE_DEPT_NAME", orgBean.getStr("ORG_NAME"));
                accountDeptRoleTempBean.set("ACCOUNTROLE_ROLE_ID", roleIdList.get(i));
                accountDeptRoleTempBean.set("ACCOUNTROLE_ROLE_NAME", roleNameList.get(i));
                accountDeptRoleTempBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
                accountDeptRoleModelList.add(accountDeptRoleTempBean);
            }
        }

        List<String> accountIdList = new ArrayList<>();
        for (DynaBean eachBean : accountDeptRoleModelList) {
            accountIdList.add(eachBean.getStr("ACCOUNTROLE_ACCOUNT_ID"));
        }

        List<DynaBean> existsAccountDeptRoleList = metaService.select("JE_RBAC_ACCOUNTROLE", ConditionsWrapper.builder()
                .in("ACCOUNTROLE_ACCOUNT_ID", accountIdList));
        List<DynaBean> needRemovedBeanList = new ArrayList<>();
        for (DynaBean eachExistsBean : existsAccountDeptRoleList) {
            for (DynaBean eachNeedInsertBean : accountDeptRoleModelList) {
                if (eachExistsBean.getStr("ACCOUNTROLE_ACCOUNT_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_ACCOUNT_ID"))
                        && eachExistsBean.getStr("ACCOUNTROLE_ROLE_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_ROLE_ID"))) {
                    needRemovedBeanList.add(eachNeedInsertBean);
                }
            }
        }
        accountDeptRoleModelList.removeAll(needRemovedBeanList);
        metaService.insertBatch("JE_RBAC_ACCOUNTROLE", accountDeptRoleModelList);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public void operationUserWithAccount(String opType, String orgId, String userIds) throws OrganException, AccountException {
        DynaBean orgBean = metaService.selectOne("JE_RBAC_ORG", ConditionsWrapper.builder().eq("JE_RBAC_ORG_ID", orgId));
        if (orgBean == null) {
            throw new OrganException("不存在此机构，请确认！");
        }
        //启用操作判断机构状态
        if ((OperationType.OPTYPE_ENABLEACCESS.getCode().equals(opType) || OperationType.OPTYPE_ENABLE.getCode().equals(opType)) && "0".equals(orgBean.getStr("SY_STATUS"))) {
            throw new OrganException("该人员表绑定的机构已被禁用，请先启用！");
        }
        //获取到映射的资源表和资源表主键
        String tableCode = orgBean.getStr("ORG_RESOURCETABLE_CODE");
        String tableIdCode = orgBean.getStr("ORG_FIELD_PK");
        String accountUserStatusField = orgBean.getStr("ORG_ACCOUNT_STATUS");
        String accountAccessStatusField = orgBean.getStr("ORG_ACCOUNTACCESS_STATUS");
        if (Strings.isNullOrEmpty(tableCode) || Strings.isNullOrEmpty(tableIdCode)) {
            throw new AccountException("Can't find the tableCode or pk code from the org mapping!");
        }
        Map<String, DynaBean> hasAccountMap = new HashMap<>();
        List<DynaBean> accountBeanList = null;
        List<DynaBean> userBeans = null;
        if (Strings.isNullOrEmpty(userIds)) {
            //机构调用禁用逻辑单独处理
            accountBeanList = metaService.select("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("SY_ORG_ID", orgId));
            for (DynaBean eachAccountBean : accountBeanList) {
                hasAccountMap.put(eachAccountBean.getStr("USER_ASSOCIATION_ID"), eachAccountBean);
            }
            userBeans = metaService.select(tableCode, ConditionsWrapper.builder());
        } else {
            List<String> userIdList = Arrays.asList(userIds.split(ArrayUtils.SPLIT));
            accountBeanList = metaService.select("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("USER_ASSOCIATION_ID", userIdList));
            for (DynaBean eachAccountBean : accountBeanList) {
                hasAccountMap.put(eachAccountBean.getStr("USER_ASSOCIATION_ID"), eachAccountBean);
            }
            userBeans = metaService.select(tableCode, ConditionsWrapper.builder().in(tableIdCode, userIdList));
        }

        List<String> disableAccountIdList = new ArrayList<>();
        List<String> disableUserIdList = new ArrayList<>();
        for (DynaBean eachUserBean : userBeans) {
            if (OperationType.OPTYPE_ENABLEACCESS.getCode().equals(opType) && eachUserBean.getStr(accountUserStatusField).equals("0")) {
                throw new AccountException("该人员已被禁用，请先启用！");
            }
            if (hasAccountMap.containsKey(eachUserBean.getStr(tableIdCode))) {
                //已存在账号，同时禁用用户和账号
                disableAccountIdList.add(hasAccountMap.get(eachUserBean.getStr(tableIdCode)).getStr("JE_RBAC_ACCOUNT_ID"));
            }
            disableUserIdList.add(eachUserBean.getStr(tableIdCode));
        }

        if (opType.equals(OperationType.OPTYPE_ENABLEACCESS.getCode())) {
            openAccount(orgId, userIds, null);
        } else if (opType.equals(OperationType.OPTYPE_DISABLEACCESS.getCode())) {
            disableAccessUserWithAccount(disableAccountIdList, disableUserIdList, tableCode, tableIdCode, accountAccessStatusField);
        } else if (opType.equals(OperationType.OPTYPE_ENABLE.getCode())) {
            enableUserWithAccount(disableAccountIdList, disableUserIdList, tableCode, tableIdCode, accountUserStatusField);
        } else if (opType.equals(OperationType.OPTYPE_DISABLE.getCode())) {
            disableUserWithAccount(disableAccountIdList, disableUserIdList, tableCode, tableIdCode, accountUserStatusField, accountAccessStatusField);
        } else if (opType.equals(OperationType.OPTYPE_DELETE.getCode())) {
            deleteUserWithAccount(disableAccountIdList, disableUserIdList, tableCode, tableIdCode);
        }
    }

    /***
     * 外部机构用户启用
     * @param disableAccountIdList
     * @param disableUserIdList
     * @param tableCode
     * @param tableIdCode
     * @param userStatus
     * @throws AccountException
     */
    @Transactional(rollbackFor = {RuntimeException.class})
    public void enableUserWithAccount(List<String> disableAccountIdList, List<String> disableUserIdList, String tableCode, String tableIdCode, String userStatus) {
        if (disableAccountIdList != null && disableAccountIdList.size() > 0) {
            metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET USER_STATUS='1' WHERE JE_RBAC_ACCOUNT_ID IN ({0})", disableAccountIdList);
        }
        if (disableUserIdList != null && disableUserIdList.size() > 0) {
            metaService.executeSql("UPDATE " + tableCode + " SET " + userStatus + "='1'  WHERE " + tableIdCode + " IN ({0})", disableUserIdList);
        }
    }


    /***
     * 外部机构用户禁用
     * @param disableAccountIdList
     * @param disableUserIdList
     * @param tableCode
     * @param tableIdCode
     * @param userStatus
     * @param accessStatus
     * @throws AccountException
     */
    @Transactional(rollbackFor = {RuntimeException.class})
    public void disableUserWithAccount(List<String> disableAccountIdList, List<String> disableUserIdList, String tableCode, String tableIdCode, String userStatus, String accessStatus) {
        if (disableAccountIdList != null && disableAccountIdList.size() > 0) {
            metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET SY_STATUS='0',USER_STATUS='0' WHERE JE_RBAC_ACCOUNT_ID IN ({0})", disableAccountIdList);
            metaService.executeSql("UPDATE JE_RBAC_ACCOUNTDEPT SET SY_STATUS='0' WHERE ACCOUNTDEPT_ACCOUNT_ID IN ({0})", disableAccountIdList);
        }
        if (disableUserIdList != null && disableUserIdList.size() > 0) {
            metaService.executeSql("UPDATE " + tableCode + " SET " + userStatus + "='0'," + accessStatus + "='0'  WHERE " + tableIdCode + " IN ({0})", disableUserIdList);
        }
    }

    /***
     * 外部机构用户-禁止访问系统
     * @param disableAccountIdList
     * @param disableUserIdList
     * @param tableCode
     * @param tableIdCode
     * @param accessStatus
     * @throws AccountException
     */
    @Transactional(rollbackFor = {RuntimeException.class})
    public void disableAccessUserWithAccount(List<String> disableAccountIdList, List<String> disableUserIdList, String tableCode, String tableIdCode, String accessStatus) {
        if (disableAccountIdList != null && disableAccountIdList.size() > 0) {
            metaService.executeSql("UPDATE JE_RBAC_ACCOUNT SET SY_STATUS='0' WHERE JE_RBAC_ACCOUNT_ID IN ({0})", disableAccountIdList);
            metaService.executeSql("UPDATE JE_RBAC_ACCOUNTDEPT SET SY_STATUS='0' WHERE ACCOUNTDEPT_ACCOUNT_ID IN ({0})", disableAccountIdList);
        }
        if (disableUserIdList != null && disableUserIdList.size() > 0) {
            metaService.executeSql("UPDATE " + tableCode + " SET " + accessStatus + "='0'  WHERE " + tableIdCode + " IN ({0})", disableUserIdList);
        }
    }

    /***
     * 外部机构用户删除
     * @param disableAccountIdList
     * @param disableUserIdList
     * @param tableCode
     * @param tableIdCode
     * @throws AccountException
     */
    @Transactional(rollbackFor = {RuntimeException.class})
    public void deleteUserWithAccount(List<String> disableAccountIdList, List<String> disableUserIdList, String tableCode, String tableIdCode) {
        if (disableAccountIdList != null && disableAccountIdList.size() > 0) {
            metaService.delete("JE_RBAC_ACCOUNTDEPT", ConditionsWrapper.builder().in("ACCOUNTDEPT_ACCOUNT_ID", disableAccountIdList));
            metaService.delete("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("JE_RBAC_ACCOUNT_ID", disableAccountIdList));
            metaService.delete("JE_RBAC_ACCOUNTROLE", ConditionsWrapper.builder().in("ACCOUNTROLE_ACCOUNT_ID", disableAccountIdList));
        }
        if (disableUserIdList != null && disableUserIdList.size() > 0) {
            metaService.delete(tableCode, ConditionsWrapper.builder().in(tableIdCode, disableUserIdList));
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public void removeOrg(String orgIds) {
        List<String> orgIdList = Splitter.on(",").splitToList(orgIds);
        metaService.delete("JE_RBAC_ORG", ConditionsWrapper.builder().in("JE_RBAC_ORG_ID", orgIdList));
        metaService.delete("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().in("SY_ORG_ID", orgIdList));
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public void updateUserName(DynaBean userBean) {
        //通过 tableCode 获取机构orgId,若当前外部用户表未绑定机构，则不更新全局其他数据该名称字段
        DynaBean orgBean = getOrgByTableCode(userBean.getTableCode());
        if (orgBean == null) {
            return;
        }
        String userId = userBean.getPkValue();
        String userName = orgBean.getStr("ORG_ACCOUNT_NAME");
        DynaBean sourceUserBean = metaService.selectOne(userBean.getTableCode(), ConditionsWrapper.builder().eq(userBean.getPkCode(), userBean.getPkValue()));
        if (!sourceUserBean.getStr(userName).equals(userBean.getStr(userName))) {
            //需要修改 公司表-管理员
            List<DynaBean> listManagerBean = metaService.select("JE_RBAC_COMPANY", ConditionsWrapper.builder().like("COMPANY_MANAGER_ID", "%" + userId + "%"));
            if (listManagerBean != null && listManagerBean.size() > 0) {
                for (DynaBean eachCompanyBean : listManagerBean) {
                    List<String> managerIdList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MANAGER_ID").split(ArrayUtils.SPLIT));
                    List<String> managerNameList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MANAGER_NAME").split(ArrayUtils.SPLIT));
                    int indexCount = managerIdList.indexOf(userId);
                    managerNameList.set(indexCount, userBean.getStr("USER_NAME"));
                    metaService.executeSql("UPDATE JE_RBAC_COMPANY SET COMPANY_MANAGER_NAME={0} WHERE JE_RBAC_COMPANY_ID={1} ", StringUtils.join(managerNameList, ","), eachCompanyBean.getStr("JE_RBAC_COMPANY_ID"));
                }
            }
            //公司表-主管领导
            List<DynaBean> listBean = metaService.select("JE_RBAC_COMPANY", ConditionsWrapper.builder().like("COMPANY_MAJOR_ID", "%" + userId + "%"));
            if (listBean != null && listBean.size() > 0) {
                for (DynaBean eachCompanyBean : listBean) {
                    List<String> zgIdList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MAJOR_ID").split(ArrayUtils.SPLIT));
                    List<String> zgNameList = Arrays.asList(eachCompanyBean.getStr("COMPANY_MAJOR_NAME").split(ArrayUtils.SPLIT));
                    int indexCount = zgIdList.indexOf(userId);
                    zgNameList.set(indexCount, userBean.getStr(userName));
                    metaService.executeSql("UPDATE JE_RBAC_COMPANY SET COMPANY_MAJOR_NAME={0} WHERE JE_RBAC_COMPANY_ID={1} ", StringUtils.join(zgNameList, ","), eachCompanyBean.getStr("JE_RBAC_COMPANY_ID"));
                }
            }

            //部门主管
            List<DynaBean> listDeptBean = metaService.select("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().like("DEPARTMENT_MAJOR_ID", "%" + userId + "%"));
            if (listDeptBean != null && listDeptBean.size() > 0) {
                for (DynaBean eachBean : listDeptBean) {
                    List<String> zgIdList = Arrays.asList(eachBean.getStr("DEPARTMENT_MAJOR_ID").split(ArrayUtils.SPLIT));
                    List<String> zgNameList = Arrays.asList(eachBean.getStr("DEPARTMENT_MAJOR_NAME").split(ArrayUtils.SPLIT));
                    int indexCount = zgIdList.indexOf(userId);
                    zgNameList.set(indexCount, userBean.getStr(userName));
                    metaService.executeSql("UPDATE JE_RBAC_DEPARTMENT SET DEPARTMENT_MAJOR_NAME={0} WHERE JE_RBAC_DEPARTMENT_ID={1} ", StringUtils.join(zgNameList, ","), eachBean.getStr("JE_RBAC_DEPARTMENT_ID"));
                }
            }

            //部门人员关联表（直接领导）
            metaService.executeSql("UPDATE JE_RBAC_DEPTUSER SET DEPTUSER_DIRECTLEADER_NAME={0} WHERE DEPTUSER_DIRECTLEADER_ID = {1}", userBean.getStr(userName), userId);
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public void syncAccountBy(DynaBean userBean) {
        //通过 tableCode 获取机构orgId,若当前外部用户表未绑定机构，则不更新该用户账号信息
        DynaBean orgBean = getOrgByTableCode(userBean.getTableCode());
        if (orgBean == null) {
            return;
        }
        String tableCode = orgBean.getStr("ORG_RESOURCETABLE_CODE");
        String tableIdCode = orgBean.getStr("ORG_FIELD_PK");
        if (Strings.isNullOrEmpty(tableCode) || Strings.isNullOrEmpty(tableIdCode)) {
            throw new AccountException("Can't find the tableCode or pk code from the org mapping!");
        }
        //获取映射字段，账号名称、账号编码，账号手机、账号邮箱、账号头像,账号性别
        String accountNameField = orgBean.getStr("ORG_ACCOUNT_NAME");
        String accountCodeField = orgBean.getStr("ORG_ACCOUNT_CODE");
        String accountPhoneField = orgBean.getStr("ORG_ACCOUNT_PHONE");
        String accountEmailField = orgBean.getStr("ORG_ACCOUNT_MAIL");
        String accountAvatarField = orgBean.getStr("ORG_ACCOUNT_AVATAR");
        String accountSexField = orgBean.getStr("ORG_ACCOUNT_SEX");

        DynaBean accountBean = metaService.selectOne("JE_RBAC_ACCOUNT", ConditionsWrapper.builder().eq("USER_ASSOCIATION_ID", userBean.getStr(tableIdCode)));
        if (accountBean == null) {
            return;
        }
        //开发者机构-控制-校验唯一性
        if (OrgType.DEVELOP_ORG_ID.getCode().equals(orgBean.getStr("JE_RBAC_ORG_ID"))) {
            rbacAccountService.checkAccountCodeUnique(accountBean.getStr("JE_RBAC_ACCOUNT_ID"), userBean.getStr(accountCodeField));
            rbacAccountService.checkAccountPhoneUnique(accountBean.getStr("JE_RBAC_ACCOUNT_ID"), userBean.getStr(accountPhoneField));
            rbacAccountService.checkAccountEmailUnique(accountBean.getStr("JE_RBAC_ACCOUNT_ID"), userBean.getStr(accountEmailField));
        }
        if (userBean != null) {
            metaService.executeSql(
                    "UPDATE JE_RBAC_ACCOUNT SET ACCOUNT_NAME={0},ACCOUNT_CODE={1},ACCOUNT_PHONE={2},ACCOUNT_MAIL={3},ACCOUNT_AVATAR={4} ,ACCOUNT_SEX={5} WHERE JE_RBAC_ACCOUNT_ID ={6}",
                    userBean.getStr(accountNameField), userBean.getStr(accountCodeField), userBean.getStr(accountPhoneField), userBean.getStr(accountEmailField), userBean.getStr(accountAvatarField), userBean.getStr(accountSexField), accountBean.getStr("JE_RBAC_ACCOUNT_ID"));
        }

    }


}
